/*
	Copyright (C) 2013 Pontificia Universidad Catolica del Peru
	contact: http://avatar.inf.pucp.edu.pe/realidad-aumentada/
	address contact: Av. Universitaria 1801, San Miguel, Lima-Peru.
	
	This file is part of UbicAR PUCP.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with This program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
	Author: Pedro Carrión Castagnola
	Pontificia Universidad Catolica del Peru
	Direccion de Informatica Academica
	
	Modified by: Alvaro Roger Agüero Sánchez, Rodolfo Javier Galvez Meza
	Pontificia Universidad Catolica del Peru
	Departamento de Ingeniería
*/

package org.grupoavatar.guiaubicua;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

import org.grupoavatar.guiaubicua.entidades.ARMarker;
import org.grupoavatar.guiaubicua.entidades.ListaPOIAdapter;
import org.grupoavatar.guiaubicua.entidades.ListaPOIRow;
import org.grupoavatar.guiaubicua.entidades.MarkerComparator;
import org.grupoavatar.guiaubicua.mix.DataView;
import org.grupoavatar.guiaubicua.mix.Marker;
import org.grupoavatar.guiaubicua.mix.MixState;
import org.grupoavatar.guiaubicua.mix.data.DataSource.DATASOURCE;
import org.grupoavatar.guiaubicua.punto.MasterActivity;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;


public class VLista extends SherlockActivity {

	private ListView listV;

	private ListaPOIRow listapoi_data[];
	private Vector<Integer> selectedItemIndex;

	private DataView dataView;

	private int ordenamiento = MarkerComparator.ORDENAMIENTO_ALFABETICO;
	private boolean ordenar_eventos = true;
	
	private static List<Marker> markerList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// obtengo los pois actuales a partir de variables globales
		dataView = VInicial.dataView;

		selectedItemIndex = new Vector<Integer>();

		this.setContentView(R.layout.lista);
		
		//header
//		Button btnLogo = (Button) findViewById(R.id.btnLogo);
//		btnLogo.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				DataView.volverInicio = true;
//				finish();
//			}
//		});
		getSherlock().getActionBar().setTitle("Lista");
		
		listV = (ListView) findViewById(R.id.lista);
		
		markerList = dataView.getDataHandler().getMarkerList();
		if ((markerList != null) && (!markerList.isEmpty())) {
			establecerLista(ordenamiento);
		}
	}

	private void establecerLista(int ordenamiento) {
		
		//ordenamiento
		if (ordenar_eventos)	{
			//si todos son eventos, no ordenar (se utiliza el ordanamiento con el que viene de json, por fechas))
			for (int i = 0; i < markerList.size(); i++) {
				Marker ma = markerList.get(i);
				if (ma.getDatasource() != DATASOURCE.EVENTOSURL) {
					Collections.sort(markerList, new MarkerComparator(ordenamiento));
					break;
				}
			}
		}
		else	{
			Collections.sort(markerList, new MarkerComparator(ordenamiento));
		}
		
		int markerListSize = markerList.size();

		// agrego los pois a la lista
		List<ListaPOIRow> dataList = new ArrayList<ListaPOIRow>();
		
		selectedItemIndex.clear();

		for (int i = 0; i < markerListSize; i++) {
			Marker ma = markerList.get(i);
			if (ma.isActive()) {
//				if (MarkerComparator.ultipoOrdenamientoSeleccionado == MarkerComparator.ORDENAMIENTO_DISTANCIA) {
					dataList.add(new ListaPOIRow(ma.getIcon(), ma.distanciaInmediata(), ma.getDistance()));
//				} else {
//					dataList.add(new ListaPOIRow(ma.getIcon(), ma.getTitle(), ma.getDistance()));
//				}
				selectedItemIndex.add(i);
			}
		}
		
		listapoi_data = dataList.toArray(new ListaPOIRow[dataList.size()]);
		
		ListaPOIAdapter adapter = new ListaPOIAdapter(this,
				R.layout.listapoi_row, listapoi_data);
		listV.setAdapter(adapter);

		listV.setVerticalFadingEdgeEnabled(true); // Make sure that fading is
													// displayed on samsung
													// devices

		listV.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> l, View v, int position,
					long id) {
				Integer POIIndex = position < selectedItemIndex.size() ? selectedItemIndex
						.get(position) : -1;
				if (POIIndex != -1) {
					Intent i = new Intent(VInicial.getContext(), VDownloading.class);
					i.putExtra("sigV", "poi");
					//VPOI.setPoi((ArpucpPOIMarker) markerList.get(POIIndex));
//					TabGeneral.setPoi((ArpucpPOIMarker) markerList.get(POIIndex));
//					TabUbicacion.setPoi((ArpucpPOIMarker) markerList.get(POIIndex));
//					TabServicios.setPoi((ArpucpPOIMarker) markerList.get(POIIndex));
					MasterActivity._poi = (ARMarker)markerList.get(POIIndex);
					MasterActivity._markerListTemporal = null;
					MasterActivity._bpoi = null;
					MasterActivity._poiHijoAnterior = null;
					i.putExtra("idPOI", "setted");
					startActivity(i);
				}
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		
		if (DataView.volverInicio)	{
			finish();
			return;
		}
		
		int estadoDescarga = VInicial.dataView.getEstado();
		if (estadoDescarga != MixState.DONE) {
			Intent i = new Intent(VInicial.getContext(), VDownloading.class);
			i.putExtra("sigV", "lista");
			startActivity(i);
			this.finish();
			return;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		int base = Menu.FIRST;
//		MenuItem item1 = menu.add(base, base, base, getString(R.string.menu_item_1)); //buscar por categoria
//		MenuItem item2 =menu.add(base, base+1, base+1,  getString(R.string.menu_item_2)); //buscar por servicios
//		MenuItem item3 = menu.add(base, base + 2, base + 2, getString(R.string.menu_item_orden_cat)); //ordenar por categoria
//		MenuItem item4 = menu.add(base, base + 3, base + 3, getString(R.string.menu_item_orden_alf)); //ordenar alfabeticamente
//		MenuItem item5 = menu.add(base, base + 4, base + 4, getString(R.string.menu_item_orden_dis)); //ordenar por distancia
//
//		item1.setIcon(R.drawable.ic_menu_filtrar);
//		item2.setIcon(android.R.drawable.ic_menu_share);
//		item3.setIcon(android.R.drawable.ic_menu_gallery);
//		item4.setIcon(android.R.drawable.ic_menu_sort_alphabetically);
//		item5.setIcon(android.R.drawable.ic_menu_sort_by_size);
		
		MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.menu_lista, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.listaMenuCategoria: //buscar por categoria
			Intent i = new Intent(VInicial.getContext(), VFiltro.class);
			startActivity(i);
			break;
		case R.id.listaMenuServicios: //Buscar por servicio
			i = new Intent(VInicial.getContext(), VServicios.class);
			startActivity(i);
			break;
		case R.id.listaMenuOrdenarCategoria: //ordenar por categoria
			if ((markerList != null) && (!markerList.isEmpty())) {
				ordenamiento = MarkerComparator.ORDENAMIENTO_CATEGORIA;
				ordenar_eventos = false;
				establecerLista(ordenamiento);
			}
			break;
		case R.id.listaMenuOrdenarAlfabeticamente: //ordenar alfabeticamente
			if ((markerList != null) && (!markerList.isEmpty())) {
				ordenamiento = MarkerComparator.ORDENAMIENTO_ALFABETICO;
				ordenar_eventos = false;
				establecerLista(ordenamiento);
			}
			break;
		case R.id.listaMenuOrdenarDistancia: //ordenar por distancia
			if ((markerList != null) && (!markerList.isEmpty())) {
				ordenamiento = MarkerComparator.ORDENAMIENTO_DISTANCIA;
				ordenar_eventos = false;
				establecerLista(ordenamiento);
			}
			break;
		}
		return true;
	}
	
}